package com.ws.shop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.ws.shop.bean.Page;
import com.ws.shop.dao.BaseDao;
import com.ws.shop.util.JdbcUtil;

public class BaseDaoImpl extends JdbcTemplate implements BaseDao{
	
	@Resource(name="dataSource")
	public void setDataSource(DataSource dataSource) {
		super.setDataSource(dataSource);
	}
	
	/**
	 * 分页查询
	 * @param page 保存分页数据对象
	 * @param count_sql 查询总记录数
	 * @param list_sql 查询分页数据
	 */
	public Page findPage(long pageno,int pagesize,String count_sql,StringBuilder list_sql){
		Page page = new Page(pageno);
		if(pagesize > 0){
			page.setPagesize(pagesize);
		}
		page.setTotalnum(this.queryForInt(count_sql));
		if(page.getTotalnum() > 0)
			page.setData(this.queryForList(
					list_sql.append(" limit ").append(page.getStartrownum()).append(",").append(page.getPagesize()).toString()));
		return page;
	}
	
	/**
	 * 分页查询
	 * @param page 保存分页数据对象
	 * @param count_sql 查询总记录数
	 * @param list_sql 查询分页数据
	 * @param args 预查询语句参数值
	 */
	public Page findPage(long pageno,int pagesize,String count_sql,StringBuilder list_sql,Object... args){
		Page page = new Page(pageno);
		if(pagesize > 0){
			page.setPagesize(pagesize);
		}
		page.setTotalnum(this.queryForInt(count_sql,args));
		if(page.getTotalnum() > 0)
			page.setData(this.queryForList(
					list_sql.append(" limit ").append(page.getStartrownum()).append(",").append(page.getPagesize()).toString(),args));
		return page;
	}
	
	/**
	 * 查询指定开始记录的后n条记录
	 * @param conn
	 * @param sql
	 * @param args
	 * @return
	 * @throws Exception
	 */
	public List<Map<String,Object>> findList(int startrow,int size,StringBuilder list_sql,Object... args){
		return this.queryForList(list_sql.append(" limit ").append(startrow).append(",").append(size).toString(),args);
	}
	
	public Object find(Connection conn, String sql, Object[] args) throws Exception {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			rs = ps.executeQuery();
			Object obj = null;
			if (rs.next()) {
				obj = rowMapper(rs);
			}
			return obj;
		} catch (SQLException e) {
			throw new SQLException(e.getMessage(), e);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception(ex.getMessage(), ex);
		} finally {
			JdbcUtil.close(rs, ps, null);
		}
	}

	protected Object rowMapper(ResultSet rs) throws SQLException{
		return null;
	}

	public int update(Connection conn, String sql, Object[] args) throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			throw new SQLException(e.getMessage(), e);
		} finally {
			JdbcUtil.close(rs, ps, null);
		}
	}

	public List<Object> query(String sql) throws SQLException {
		List<Object> list = new ArrayList<Object>();
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = this.getDataSource().getConnection().createStatement();
			rs = stmt.executeQuery(sql);
			// 获取数据库表结构
			ResultSetMetaData rsm = rs.getMetaData();
			// 取得数据库的列数
			int col = rsm.getColumnCount();
			// 生成col长度的Object数组
			Object[] obj = new Object[col];
			// 遍历结果集，将结果存入Object数组
			while (rs.next()) {
				for (int i = 0; i < col; i++) {
					obj[i] = rs.getObject(i + 1);
				}
				list.add(obj);
			}
		} catch (SQLException e) {
			throw new SQLException(e.getMessage(), e);
		} finally {
			JdbcUtil.close(rs, stmt, null);
		}
		return list;
	}

	public List<Object> findConllect(Connection conn, String sql, Object[] args) throws Exception {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			rs = ps.executeQuery();
			ResultSetMetaData rsm = rs.getMetaData();
			// 取得数据库的列数
			int col = rsm.getColumnCount();
			// 生成col长度的Object数组
			Object[] obj = new Object[col];
			List<Object> list = new ArrayList<Object>();
			// 遍历结果集，将结果存入Object数组
			while (rs.next()) {
				for (int i = 0; i < col; i++) {
					obj[i] = rs.getObject(i + 1);
				}
				list.add(obj);
			}
			return list;
		} catch (SQLException e) {
			throw new SQLException(e.getMessage(), e);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception(ex.getMessage(), ex);
		} finally {
			JdbcUtil.close(rs, ps, null);
		}
	}
	
	public long getCount(Connection connect,String s) throws SQLException{
		Statement stmt = connect.createStatement();
		ResultSet r = stmt.executeQuery(s);
		long totalnum = 0;
		if (r.next()) {
			totalnum = r.getLong(1);
		}
		JdbcUtil.close(r,stmt,null);
		return totalnum;
	}
	
}
